package com.example.locationreport.locationreport.utils.voice;

import android.content.Context;
import android.text.TextUtils;

import com.example.locationreport.locationreport.utils.LogUtils;
import com.unisound.client.SpeechConstants;
import com.unisound.client.SpeechSynthesizer;
import com.unisound.client.SpeechSynthesizerListener;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.regex.Pattern;


/**
 * 离线语音合成工具类
 *
 * @author liub
 */
public class SpeakUtils {

    /**
     * appKey
     */
    public static final String appKey = "x6z7w2qundwtayyzwidvzaslilugerav2xwdlbih";

    /**
     * secret
     */
    public static final String secret = "07cee99ca4dbf0511f420197cd7936f6";

    private static SpeakUtils instance;

    private SpeechSynthesizer mTTSPlayer;

    /**
     * 存储待播放的文字信息
     */
    private BlockingDeque<String> speechQueue = new LinkedBlockingDeque<>();

    private boolean released = false;

    protected OfflineResource offlineResource;

    /**
     * 判断当前语音是否播放完成
     */
    private boolean isSpeaking = false;

    /**
     * 用来判断初始化是否成功
     */
    private boolean isInitSuccess = false;

    private SpeakUtils() {

    }

    public static SpeakUtils getInstance() {
        if (instance == null) {
            synchronized (SpeakUtils.class) {
                if (instance == null) {
                    instance = new SpeakUtils();
                }
            }
        }
        return instance;
    }
    /**
     * 初始化引擎
     *
     * @author JPH
     */
    public void init(Context context) {
        initSpeech(context , 50 , 52);
    }

    /**
     * 初始化引擎
     *
     * @author JPH
     */
    public void init(Context context , int pitch) {
        initSpeech(context , pitch , 52);
    }


    /**
     * 初始化引擎
     *
     * @author JPH
     */
    public void init(Context context , int pitch , int speed) {
        initSpeech(context , pitch , speed);
    }


    private void initSpeech(Context context , int pitch , int speed){

        offlineResource = new OfflineResource(context);

        // 初始化语音合成对象
        mTTSPlayer = new SpeechSynthesizer(context, appKey, secret);
        // 设置本地合成
        mTTSPlayer.setOption(SpeechConstants.TTS_SERVICE_MODE, SpeechConstants.TTS_SERVICE_MODE_LOCAL);
        // 音调
        mTTSPlayer.setOption(SpeechConstants.TTS_KEY_VOICE_PITCH, pitch);
        // 语速
        mTTSPlayer.setOption(SpeechConstants.TTS_KEY_VOICE_SPEED, speed);
        // 音量
        mTTSPlayer.setOption(SpeechConstants.TTS_KEY_VOICE_VOLUME, 100);

        // 设置前端模型
        mTTSPlayer.setOption(SpeechConstants.TTS_KEY_FRONTEND_MODEL_PATH, offlineResource.getModelFilename());
        // 设置后端模型
        mTTSPlayer.setOption(SpeechConstants.TTS_KEY_BACKEND_MODEL_PATH, offlineResource.getBackFilename());
        // 设置回调监听
        mTTSPlayer.setTTSListener(new SpeechSynthesizerListener() {
            @Override
            public void onEvent(int type) {
                switch (type) {
                    case SpeechConstants.TTS_EVENT_INIT:
                        // 初始化成功回调
                        isInitSuccess = true;
                        // 初始化完成之后更新下队列
                        try {
                            updateSpeech();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case SpeechConstants.TTS_EVENT_SYNTHESIZER_START:
                        // 开始合成回调
                        break;
                    case SpeechConstants.TTS_EVENT_SYNTHESIZER_END:
                        // 合成结束回调
                        break;
                    case SpeechConstants.TTS_EVENT_BUFFER_BEGIN:
                        // 开始缓存回调
                        break;
                    case SpeechConstants.TTS_EVENT_BUFFER_READY:
                        // 缓存完毕回调
                        break;
                    case SpeechConstants.TTS_EVENT_PLAYING_START:
                        // 开始播放回调
                        isSpeaking = true;
                        break;
                    case SpeechConstants.TTS_EVENT_PLAYING_END:
                        // 播放完成回调
                        isSpeaking = false;
                        try {
                            updateSpeech();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case SpeechConstants.TTS_EVENT_PAUSE:
                        // 暂停回调
                        break;
                    case SpeechConstants.TTS_EVENT_RESUME:
                        // 恢复回调
                        break;
                    case SpeechConstants.TTS_EVENT_STOP:
                        // 停止回调
                        break;
                    case SpeechConstants.TTS_EVENT_RELEASE:
                        // 释放资源回调
                        break;
                    default:
                        break;
                }

            }

            @Override
            public void onError(int type, String errorMSG) {
                isSpeaking = false;
                // 语音合成错误回调
                LogUtils.e("语音合成错误回调TTS" , "onError __ type : " + type + " errorMsg : " + errorMSG);
            }
        });
        // 初始化合成引擎
        try {
            mTTSPlayer.init("");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 停止播放
     *
     * @author JPH
     */
    public void stop() {
        mTTSPlayer.stop();
    }

    /**
     * 播放
     *
     * @author JPH
     */
    public void play(String content) {
        play(returnResultMultiple(content) , PLAY_MODE.QUEUED);
    }

    private static String returnResultMultiple(String str) {
        if (TextUtils.isEmpty(str))
            return "";

        String value = str ;

        Pattern compile = Pattern.compile("[a-zA-Z]");

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (compile.matcher(String.valueOf(ch)).matches()) {
                value = value.replace(ch + "", ch + "-");
            }
        }
        return value;
    }

    public void play(String content, PLAY_MODE playMode) {
        switch (playMode) {
            case QUEUED:
                playQueued(content);
                break;
            case IMMEDIATELY:
                playImmediately(content);
                break;
        }
    }

    private void updateSpeech()  {
        // 如果云知声引擎初始化失败，直接结束
        if (!isInitSuccess) {
            LogUtils.e("语音合成" , "未初始化");
            return;
        }
        // 其他队列（包括越界、限高、停止点、停车位、导航）
        if (!speechQueue.isEmpty()) {
            try {
                String message = speechQueue.takeLast();
                speechQueue.clear();
                speak(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void speak(String content) {
        try {
            mTTSPlayer.playText(content);
        }catch (IllegalThreadStateException e){
            e.getMessage();
        }
    }

    public void playQueued(String content) {
        try {
            speechQueue.putLast(content);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (!isSpeaking) {
            updateSpeech();
            isSpeaking = true;
        }
    }

    public void playImmediately(String content) {
        speak(content);
    }

    /**
     * 释放资源
     */
    public void release() {
        // 主动释放离线引擎
        if (released) {
            return;
        }
        if (mTTSPlayer != null) {
            mTTSPlayer.stop();
            mTTSPlayer.release(SpeechConstants.TTS_RELEASE_ENGINE, null);
        }
        instance = null;
        released = true;
    }


    public enum PLAY_MODE {
        QUEUED,
        IMMEDIATELY
    }
}